<?php
			
	/* SVN FILE: $Id: view.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/view.php $
	 */

	if (!isset($sAPP) || !is_string($sAPP) || !isset($aSUITE) || !is_array($aSUITE) || !isset($aSUITE[$sAPP])) {

	   	/**
		 * Intercetto la situazione in cui viene eseguito direttamente questo script (ovvero quando
		 * questo script non e' incluso in $sAPP/view.php
		 *
		 */
		 
		fnUpdateLog('APP NOT DEFINED', 0, '', 'E');
		header('Location: ../index.php?sMsg=app-not-defined');
		die();
	} 
	 
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php

	$sViewItemLink = fnCurrentScript();
	fnViewConst($sViewItemLink);
	
	// array $aFieldsDataType
	fnFieldsDataTypeArray($sViewSelectFrom);

	// jquery.validate.min.js ** INIZIO **
	
	$sJsValidate = '';
	
	$bIncludeValidate = false;
	if (isset($aForms) && !empty($aForms)) {
		foreach ($aForms as $sForm => $aFormSettings) {
		 	if (isset($aFormSettings['aFormFieldsMandatory']) && !empty($aFormSettings['aFormFieldsMandatory'])) {
		 		$bIncludeValidate = true;
		 	}	
		 }
	}	 	

	if ($bIncludeValidate || (isset($aFieldsDataType['date']) && !empty($aFieldsDataType['date']))) {
		$sHeadContent .= "
			<script type='text/javascript' src='$sSCRIPT_ROOT_PATH/include/jquery.validate.min.js'></script>
			<script type='text/javascript' src='$sSCRIPT_ROOT_PATH/include/messages_it.js'></script>
			<script type='text/javascript' src='$sSCRIPT_ROOT_PATH/include/methods_it.js'></script>";
		
		foreach ($aForms as $iTab => $aFormSettings) {
			$bValidate = false;
			$sJsValidate = " $('#form-tab-$iTab').validate({ rules: {";	
			if (isset($aFormSettings['aFormFieldsMandatory']) && !empty($aFormSettings['aFormFieldsMandatory'])) {
				foreach ($aFormSettings['aFormFieldsMandatory'] as $sField) { // campi obbligatori
					$sRule = " required: true, ";
					if (fnCheckFieldsDataType($sField, 'date')) {
						$sRule .= " date: true, ";
					}
					$sRule = substr_replace($sRule, '', -2);
					$sJsValidate .= " $sField: { $sRule }, ";
					$bValidate = true;
				}
			}	
			if (isset($aFieldsDataType['date']) && !empty($aFieldsDataType['date'])) {
				foreach ($aFormSettings['aFormFields'] as $sField) { // inserisco qui i campi rimasti nell'array, ovvero quelli non obbligatori ma che richiedono " date: true, "
					if (in_array($sField, $aFieldsDataType['date']) && !in_array($sField, $aFormSettings['aFormFieldsMandatory'])) {
						$sRule = " required: false, date: true ";
						$sJsValidate .= " $sField: { $sRule }, ";
						$bValidate = true;
					}
				}	
			}
			if ($bValidate) {
				$sJsDocumentReady .= substr_replace($sJsValidate, '', -2)." } }); ";
			}
		}
	}
	
	// jquery.validate.min.js ** FINE **
	
	// collegamento per tornare a index.php
	$sBacklink = fnHtmlBacklinkFull('get', 'index.php', $bSEARCH_FORM_SHOW, $bTagsShow);
	
	$sHeadContent .= "
		<script type='text/javascript' src='../include/jquery.prettydate.js'></script> ";

	
	$sJsDocumentReady .= "
		setTimeout(function(){ $('.ui-message-flash').fadeOut(); }, 1800);
		
		$.prettyDate.messages = {
			now: 'adesso',
			minute: '1 minuto fa',
			minutes: $.prettyDate.template('{0} minuti fa'),
			hour: '1 ora fa',
			hours: $.prettyDate.template('{0} ore fa'),
			yesterday: 'ieri',
			days: $.prettyDate.template('{0} giorni fa'),
			weeks: $.prettyDate.template('{0} settimane fa')
		};
		
		$('.prettydate').prettyDate();
		
		$.datepicker.setDefaults($.datepicker.regional['it']);	
		
		$('.datepicker').datepicker();";
	
	
	
	// 'id' della scheda da visualizzare ($iView)
	if (isset($_GET['iView']) && !empty($_GET['iView']) && is_numeric($_GET['iView'])) {
		$iView = round($_GET['iView']);
	}
	
	
	
	// verifica del fatto che $iView sia associato ad un record nella tabella $sViewSelectFrom
	if (!empty($iView)) {
		$aData = fnCheckView($iView, $sViewSelectFrom, $sViewSelectGroupBy, 'aData');
		if (!empty($aData)) { // esiste un record associato a $iView
			$iAccessLvl = fnViewAccessLvl($iView, $aTABLE, $aTABLE_SECURITY_CHECK);
			$iTab = fnGetInt('iTab', $iTabDefault);
		
		} else {
			fnUpdateLog("RECORD NOT FOUND", $iView, $sViewSelectFrom, 'E');
	  		$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=recordnotfound';

		}

	} else {
		$iAccessLvl = fnGetAccessLvl();
		$iTab =  $iTabDefault;
	  	
	  	// Le prossime righe servono per pre-compilare i campi impostati nei filtri <input type='select'>
	  	// della pagina index.php (ad esempio per avere già compilati i campi 'Dipartimento' e
	  	// 'Unità').
	  	$aSelect = fnSettingsArray(fnReadSessionValue ('sTable', 'main-table', $sAPP), 'select');
		foreach ($aSelect as $aFilter) {
			if (!is_null(fnReadSessionValue ($aFilter['sField'], 'main-table', $sAPP))) { 
				$aData[$aFilter['sField']] = fnReadSessionValue ($aFilter['sField'], 'main-table', $sAPP);
			}
		}
	
	}
	
	if ((!empty($iView) && !empty($aData)) || empty($iView)) {
		if (isset($aTabsLabels[$iTab])) {
			
			$iTabAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab);
			
			if (is_allowed('view', $iTabAccessLvl)) {
				
				// schede nel cestino

				if (isset($aData['iTrash']) && !empty($aData['iTrash'])) {
					$html .= "<div class='ui-state-highlight ui-corner-all' style='margin-top:4px; margin-bottom:6px; margin-left:5px; padding:4px;'>
							<img src='../themes/common/images/trash16x16.png' width='16px' height='16px' style='float:left;'>
							<div style='margin-left: 25px;'><strong>".fnHtmlTrashWhen($aData['tsTrashWhen'])."</strong>".
							(!empty($aData['sTrashWhy']) ? "<br/>".$aData['sTrashWhy'] : "")."</div></div>";
				}
				
				// $sAction
				if (!empty($iView) && isset($_GET['sAction'])) {
					switch ($_GET['sAction']) {
						case 'edit':
							if (is_allowed('edit', $iTabAccessLvl)) {
								if (empty($aData['iTrash'])) {
									$sAction = $_GET['sAction'];
								} else {
									// le schede nel cestino non possono essere modificate:
									// eseguo un redirect senza specificare il parametro sAction
									fnUpdateLog("EDIT IN TRASH NOT ALLOWED", $iView, $sViewSelectFrom, 'I');
									$sRedirect = "./$sViewItemLink?iView=$iView&iTab=$iTab&sMsg=trashed";
								}
								
							} else {
								fnUpdateLog("LOW RIGHTS", $iView, $sViewSelectFrom, 'S');
								$sRedirect = "./$sViewItemLink?iView=$iView&iTab=$iTab&sMsg=low-rights";
							
							}
						break;
					}
					
				} else if (empty($iView)) {
					if (is_allowed('edit', $iTabAccessLvl)) {
						$sAction = 'edit';
					} else {
						fnUpdateLog("LOW RIGHTS", $iView, $sViewSelectFrom, 'S');
						$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=low-rights';
					} 
				}
				
				
			} else {
				fnUpdateLog("LOW RIGHTS", $iView, $sViewSelectFrom, 'S');
				if ($iTab != $iTabDefault && isset($aTabsLabels[$iTabDefault])) {
					// se $iTab è diverso da $iTabDefault  viene eseguito un redirect a
					// $sViewItemLink senza specificare alcun valore per $iTab
					$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=low-rights";
				} else {
					// se $iTab è uguale a $iTabDefault viene eseguito un redirect a index.php
					$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=low-rights';
				}	

			}
			
		} else {
			fnUpdateLog("TAB NOT FOUND [$iTab]", $iView, $sViewSelectFrom, 'E');
			if ($iTab != $iTabDefault && isset($aTabsLabels[$iTabDefault])) {
				// se $iTab è diverso da $iTabDefault  viene eseguito un redirect a
				// $sViewItemLink senza specificare alcun valore per $iTab
				$sRedirect = "./$sViewItemLink?iView=$iView&sMsg=tabnotfound";
			} else {
				// se $iTab è uguale a $iTabDefault viene eseguito un redirect a index.php
				$sRedirect = $sBacklink.($sBacklink == 'index.php' ? '?' : '&').'sMsg=tabnotfound';
			}	
		
		}
	}
	
	/** 
	 * se la variabile $sRedirect non è vuota vuol dire che si sono verificati degli errori e quindi
	 * la pagina view.php non è da visualizzare. Viene quindi eseguito un redirect.
	 */
	 
	if (!empty($sRedirect)) {
		header("Location: $sRedirect");
		die();
	}	
	
	// messaggi ricevuti da $_GET['sMsg']
	$sMessageFlash = fnMessageFlash();

	/**
	 * $sTabsHtml
	 */
	 
	$sTabsHtml = '';
	$aDisabledTabs = array();
	
	$i = 0;
	foreach ($aTabsLabels as $sKey => $sValue) {
		if (is_allowed('view', fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $sKey))) {
			list ($sLabel, $sImage) = explode ("|", $sValue);
				$sTabsHtml .= "<li><a href='#tabs-$sKey'>";
				$sTabsHtml .= "<img alt='$sLabel' border='0' src='./images/$sImage' /> $sLabel";
				$sTabsHtml .= ($sKey == $iTabUploads ? " <span id='sUploadsNum'>".fnUploadsNum($iView, $sViewSelectFrom, $iTabUploads)."</span>" : '');
				$sTabsHtml .= "</a></li>";
			// $iView è uguale a 0 quando si sta creando una nuova scheda.
			// In questo caso vengono disabilitati tutti i tab ad eccezione di quello principale ($iTabDefault)
			if ($iView == 0 && $sKey != $iTabDefault) {
				$aDisabledTabs[] = $i;
			// Quando si sta modificando una scheda vengono disabilitati tutti gli i restanti tab
			// per evitare problemi di perdita delle informazioni digitate ma non ancora inviate ('submit')
			} else if ($iView != 0 && $sKey != $iTab && $sAction == 'edit') {
				$aDisabledTabs[] = $i;
			}
		}
		$i++;			    
	}

	/**
	 * $iTabUploads
	 * Se c'è un tab riferito alla tabella 'uploads', e ne è consentita almeno la visualizzazione, inizializzo
	 * il componente 'uploadify'
	 */
	 
	if ($iTabUploads > 0 && $iView != 0) {

		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTabUploads);
		
		if (is_allowed('view', $iFieldAccessLvl)) {
			
			$sJsDocumentReady .= "
		  		function addClassOdd (sIdentifier) { 
			  		$('ul li', sIdentifier).removeClass('odd');	
			  		$('ul li:odd', sIdentifier).addClass('odd');
				}
				addClassOdd('#uploads'); ";

		  	if (empty($aData['iTrash']) && is_allowed('edit', $iFieldAccessLvl)) {
		  		
				$sHeadContent .= (empty($aData['iTrash']) ? "
					<!-- jeditable -->
					<script type='text/javascript' src='../include/jquery.jeditable.mini.js'></script>
				
					<!-- Uploadify -->
					<script type='text/javascript' src='../include/uploadify/swfobject.js'></script>
					<script type='text/javascript' src='../include/uploadify/jquery.uploadify.v2.1.4.min.js'></script> " : '');
				
				$iUploadsMaxFileSize = fnUploadsMaxFileSize();
		  				  	
			  	$sJsDocumentReady .= "
					$('#uploads-uploadify').uploadify({ 
						'uploader': '../include/uploadify/uploadify.swf',
						'script': '../include/uploads.php',
						'sizeLimit': '$iUploadsMaxFileSize',
						'multi' : true, 
						'auto' : true,
						'queueID': 'uploads-queue',
					  	'height': '26', // height of your browse button file
		  				'width': '150', // width of your browse button file
						'buttonImg': '../themes/common/images/browse.png', // browse button file
						'cancelImg': '../themes/common/images/cancel.png',
						'scriptData' : {	'iView': '$iView',
											'sViewItemLink': '$sViewItemLink',
											'sAPP': '$sAPP',
											'iAccessLvl': '$iFieldAccessLvl',
											'sUsername': '".fnReadSessionValue('sUsername')."',
											'sRedirect': 'false' },
					onProgress: function() { 
				    	$('#uploads-loader').show(); 
				    }, 
					onComplete: function (evt, queueID, fileObj, response, data) {
					 " . (is_allowed('sysop', $iAccessLvl) && fnShowDebugMsg() ? " alert(response); " : '') . "
						$('#uploads-loader').hide();
						$.getJSON(\"../include/uploads.info.php\", {	'iView': '$iView',
																		'sViewItemLink': '$sViewItemLink',
																		'sAPP': '$sAPP'	}, function (json) {
							$('#uploads-file-list').html(json[0].sHtml);
							$('#sUploadsNum').text((json[0].iUploadsNum > 0 ? '('+json[0].iUploadsNum+')' : ''));
							addClassOdd('#uploads'); ".
			  			  	fnJsFileJeditable().
		  					fnJsFileEditCancel().
		  					fnJsFileEditTrigger().
							fnJsFileRemoveClick()."
							$('.prettydate').prettyDate();
						});
					}
				}); ";
		  	}
		  	
		  	if (empty($aData['iTrash']) && is_allowed('delete', $iFieldAccessLvl)) {
		  		$sJsDocumentReady .= fnJsFileJeditable();
		  		$sJsDocumentReady .= fnJsFileEditCancel();
		  		$sJsDocumentReady .= fnJsFileEditTrigger();
		  		$sJsDocumentReady .= " var clicked; ";
		  		$sJsDocumentReady .= fnJsFileRemoveClick();
		  		$sJsDocumentReady .= fnJsFileRemoveDialog();
		  		$sJsDocumentReady .= fnJsRemoveFile($iView, $sViewItemLink);
		  		$html .= "	<div id='uploads-file-remove-dialog' title='Rimuovi allegato'>
								<p>Sei sicuro di voler rimuovere l'allegato <strong><span id='uploads-file-remove-dialog-text'></span></strong>?</p>
							</div>";
		  	}	
		}
	}
	
	/**
	 * $bTagsShow
	 */
	 
	if ($bTagsShow) { 
		
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab, 'tags');
		
		if (is_allowed('edit', $iFieldAccessLvl)) { 
			
			$sJsTagsSelectChange = fnJsTagsSelectChange('tags-sel-input');
			$sJsTagsRemoveClick = fnJsTagsRemoveClick();
			
			$sJsDocumentReady .= "

			$sJsTagsSelectChange
			$sJsTagsRemoveClick
			
			function fnTagsAdd(iTag, oObj) {
				$('#tags-loader').show();  
				$.getJSON('../include/tagging.php', {'sAction': 'tags-add-view', 'iTag': iTag, 'iView': oObj.attr('iView'), 'sViewItemLink': '$sViewItemLink', 'sAPP': '$sAPP' }, function (json) {
					if (json[0].sAction=='tags-add-view' && json[0].sError=='') { 
						$('#tags').html(json[0].sHtml);
						$sJsTagsSelectChange
						$sJsTagsRemoveClick
					} else { 
						alert ('Error: ' + json[0].sError);
					}
					$('#tags-loader').hide(); 
				});
			}

			function fnTagsRemove(oObj) {
				$('#tags-loader').show(); 	
				$.getJSON('../include/tagging.php', {'sAction': 'tags-remove-view', 'iTag': oObj.attr('iTag'), 'iView': oObj.attr('iView'), 'sViewItemLink': '$sViewItemLink', 'sAPP': '$sAPP' }, function (json) {
					if (json[0].sAction=='tags-remove-view' && json[0].sError=='') { 
						$('#tags').html(json[0].sHtml);
						$sJsTagsSelectChange
						$sJsTagsRemoveClick
					} else { 
						alert ('Error: ' + json[0].sError);
					} 
					$('#tags-loader').hide(); 
				});
			}";
		}
	}

  	// Indietro
	$sSidebarActionsTitle = "&nbsp;";
	$sSidebarActions .= fnHtmlBackButton($bSEARCH_FORM_SHOW, $bTagsShow, $aTABLE);

	// debug XMLHttpRequest
	if (is_allowed('sysop', $iAccessLvl)) {
		$sJsDocumentReady .= "
			$.ajaxSetup({\"error\": function(XMLHttpRequest, textStatus, errorThrown) {   
			      alert(textStatus);
			      alert(errorThrown);
			      alert(XMLHttpRequest.responseText);
			 }}); ";
	}	

?>